var app = getApp()
const date = new Date()
const years = []
const months = []
const days = []
for (let i = 1990; i <= date.getFullYear(); i++) {
  years.push(i)
}
for (let i = 1; i <= 12; i++) {
  months.push(i)
}
for (let i = 1; i <= 31; i++) {
  days.push(i)
}
var that
// var city = require('../../utils/allcity.js')//猫咪品种
var city=[];
var lineHeight = 0;
var endWords = "";
var isNum;
Page({
  data: {
    years: years,
    year: date.getFullYear(),
    months: months,
    month: 1,
    days: days,
    day: 1,
    year: date.getFullYear(),
    value: [9999, 0, 0],

    winWidth: 0,
    winHeight: 0,
    currentTab: 0,
    actionSheetHidden_pic: true,   //下方是否显示选择头像拍照或相册的模块
    process_title:["添加猫咪","猫咪性别","猫咪生日","猫咪备注"],
    cat_GG: "../../images/GG.png",
    cat_MM: "../../images/MM.png",
    All_variety:[],//猫的种类集合
    All_letter:["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"],
    cat_photo:"../../images/upload.png",    //猫咪头像，昵称，种类，生日，性别，绝育状态，备注
    cat_nickname:"",
    cat_variety:"中国狸花猫", 
    cat_birth: date.getFullYear()+ "-" +1 + "-" +1 , //生日默认本年度第一台
    cat_sex:"0",    
    cat_ster_statues:"0",
    cat_remark:" ",     //猫咪喜好
    sick_history:" ", //猫咪病史
    ster_class:"0",  //绝育状态和性别被选中的重新设置样式
    sex_class:"0",
    age:"不满一岁",
    "hidden": true,//选择猫咪品种
    search_content: "",//搜索内容
    scrollTopId: "A",
    enb:false,  //设置完成按钮不可用，避免跳转前多次点击
  },
  onLoad: function (options) {
    that = this;
    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      } 
    });
    //获取猫咪种类
    app.req("get_cat_variety.html", {}, function (res) {
      that.setData({ All_variety: res.mess});
    }, function (res) {
    });
  },
  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成
    // var cityChild = city.City[0];
    // that = this;
    // wx.getSystemInfo({
    //   success: function (res) {
    //     lineHeight = (res.windowHeight - 100) / 22;
    //     console.log(res.windowHeight - 100)
    //     that.setData({
    //       city: cityChild,
    //       winHeight: res.windowHeight - 40,
    //       lineHeight: lineHeight
    //     })

    //   }
    // })
  },
  onShow: function () {
    //页面显示
    // this.setData({ name: app.data.client_name });
  },
  
  //  切换tab 改变时触发 
  bindChange: function (e) {
    that.setData({ currentTab: parseInt(e.detail.current)});//不能改
    if (parseInt(e.detail.current)==1){   //当界面跳转时判断当前界面的内容是否填写完整
      if (that.data.cat_photo.substring(0, 3) == "../") {
        this.setData({ currentTab: 0 })//未传输猫咪头像,
        that.toast("未上传猫咪头像");
        return;
      }
      if (that.data.cat_nickname == null || that.data.cat_nickname == " " || that.data.cat_nickname == undefined || that.data.cat_nickname == "") {
        this.setData({ currentTab: 0 })//昵称未填写
        that.toast("猫咪昵称未填写");
        return;
      }
    }
    
    if (parseInt(e.detail.current) == 2)
    {
      if (that.data.cat_ster_statues == 0 || that.data.cat_sex == 0) {
        this.setData({ currentTab: 1 })
        app.toast_up("信息未完成选择！");
        return;
      }
    }
    if (parseInt(e.detail.current) == 3) {   //当界面跳转时判断当前界面的内容是否填写完整
      if (that.data.age =="年龄有误")
        {
        this.setData({ currentTab: 2 })
        that.toast("年龄有误");
        return;
        }
    }
    
  },
  /** 
   * 点击tab切换 
   */
  // swichNav: function (e) {
  //   var that = this;
  //   if (this.data.currentTab === e.target.dataset.current) {
  //     return false;
  //   } else {
  //     that.setData({
  //       currentTab: e.target.dataset.current
  //     })
  //   }
  // },
  choose_cat_pic:function(){//点击猫咪头像选头像
    this.setData({ actionSheetHidden_pic: false })
  },
   ActionSheet_select: function ()//下方选项取消后即隐藏
  {
    this.setData({ actionSheetHidden_pic: true})
  },
  itemclick: function (e) {//点击选项时触发
     
     if (e.currentTarget.id == 1)  //相机
     {
       wx.chooseImage({
         count: 1, // 默认9
         sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
         sourceType: ['camera'],  // 可以指定来源是相册还是相机，默认二者都有
         success: function (res) {
           // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
           var tempFilePaths = res.tempFilePaths
           that.setData({ cat_photo: tempFilePaths[0] });
         }
       })
     }
     if (e.currentTarget.id == 2) {  //相册
       wx.chooseImage({
         count: 1, // 默认9
         sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
         sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
         success: function (res) {
           // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
           var tempFilePaths = res.tempFilePaths
           that.setData({ cat_photo: tempFilePaths[0] });
         }
       })
     }
     this.setData({ actionSheetHidden_pic: true })
   },
   nickname_change:function(e){  //猫咪昵称变化时触发
     that.setData({ cat_nickname: e.detail.value })
   },
   next:function(){//点击下一步切换界面
    
    that.setData({ currentTab: that.data.currentTab+1 })
    wx.setNavigationBarTitle({ title: this.data.process_title[this.data.currentTab] })
   },
   addcat_ok:function(){//添加猫咪成功跳转到添加成功界面
    
     if (that.data.cat_photo.substring(0,3) == "../" ) {
       this.setData({ currentTab: 0 })//未传输猫咪头像,
       that.toast("未上传猫咪头像");
       return;
     }
     if (that.data.cat_nickname == null || that.data.cat_nickname == " " || that.data.cat_nickname == undefined || that.data.cat_nickname =="")
   {
       this.setData({ currentTab:0})//昵称未填写
       that.toast("猫咪昵称未填写");
       return;
   }
    //  if (that.data.cat_variety == null || that.data.cat_variety == " " || that.data.cat_variety == undefined) {
    //    this.setData({ currentTab: 1 })//品种未填写
    //    that.toast("猫咪品种未填写");
    //    return;
    //  }
     if (that.data.cat_ster_statues == 0 || that.data.cat_sex == 0) {
       this.setData({ currentTab: 1 })//品种未填写
       that.toast("信息未完成选择！");
       return;
     }
    //  if (that.data.cat_remark == null || that.data.cat_remark == undefined) {
    //    this.setData({ cat_remark:" "})//说明未填写,可以为空
    //    return; 
    //  }
     if (that.data.sick_history.trim()  == '' || that.data.sick_history==null){
       that.toast("病史未填写！");return;
    }
     console.log(that.data.cat_remark + "  " + that.data.sick_history)

    that.setData({enb:true}) //设置此按钮不可点
    app.toast("已提交")  
     wx.uploadFile({   //上传所有信息
       url: app.rootDocment + 'add_cat.html',
       filePath: that.data.cat_photo,
       name: 'file',
       formData: {
         'sessionid': wx.getStorageSync('3rd_session'),
         'openid': app.data.openid,
         'type': "avter",
         'nickname': that.data.cat_nickname,
         'variety': that.data.cat_variety,
         'sex': that.data.cat_sex,
         'ster_status': that.data.cat_ster_statues,
         'birthday': that.data.cat_birth,
         'remark': that.data.cat_remark,
         'sick_history': that.data.sick_history
       },
       success: function (res) {
         console.log(JSON.parse(res.data));
         res = JSON.parse(res.data);
         console.log(res);
         if (res.status=='error'){
           app.toast_up("提交失败!")
           that.setData({ enb: false }) 
           return;
         }else{
           app.toast("提交成功!")
           wx.redirectTo({
             url: './addcat_ok',
           })
         }
        
       },fail:function(res){
         app.toast_up("提交失败!")
         that.setData({ enb: false }) 
         console.log(res);
       }
     })
   },
   cat_birthday:function(e){//选择猫咪生日改变触发的函数
     const val = e.detail.value
     this.setData({
       year: this.data.years[val[0]],
       month: this.data.months[val[1]],
       day: this.data.days[val[2]]
     })
     this.setData({ cat_birth: this.data.years[val[0]] + "-" + this.data.months[val[1]] + "-" + this.data.days[val[2]]})
     that.cat_age(that.data.year, that.data.month, that.data.day);//计算猫咪年龄
   },
   select_sex:function(e){ //选择性别时触发的函数
    console.log(e.currentTarget.dataset.type);
    if (e.currentTarget.dataset.type=="GG"){
      that.setData({ sex_class: 1 });
      that.setData({ cat_sex: 1 });

    } if (e.currentTarget.dataset.type == "MM"){     
      that.setData({ sex_class: 2 });
      that.setData({ cat_sex: 2 });
    }
    
   },
   select_ster:function(e){   //选择是否绝育时触发
     console.log(e.currentTarget.dataset.type);
     if (e.currentTarget.dataset.type == "是") {
       that.setData({ ster_class:1});
       that.setData({ cat_ster_statues: 1 });
     } if (e.currentTarget.dataset.type == "否") {
       that.setData({ ster_class: 2 });
       that.setData({ cat_ster_statues: 2 });

     }
   },
  text_change:function(e){  //猫咪备注改变时触发
    that.setData({cat_remark:e.detail.value});
    // console.log(that.data.cat_remark);
  },
  text_change2:function(e){
    that.setData({ sick_history: e.detail.value });
  },

   cat_age:function( y, m,d){
     var n_year = date.getFullYear()
     var n_month = date.getMonth() + 1
     var n_day = date.getDate()  
     if ((n_year-y)*12*365+(n_month-m)*30+(n_day-d)<0){
       //猫还没生下来呢
       console.log("猫还没生下来呢");
       that.setData({ age: "年龄有误" });

     }else{
       var mon = (n_year - y) * 12 + (n_month - m);
       that.setData({ age: ((mon / 12) - 0.5).toFixed(0) + "岁" + mon % 12 + "个月" });
       if (((mon / 12) - 0.5).toFixed(0)<=0)
       {
         that.setData({ age: mon % 12 + "个月" });
       }
       console.log(that.data.age);
     }
   },





   //触发全部开始选择,选择品种
   chStart: function () {
     this.setData({
       trans: ".3",
       hidden: false
     })
   },
   //触发结束选择
   chEnd: function () {
     this.setData({
       trans: "0",
       hidden: true,
       scrollTopId: this.endWords
     })
     console.log(1);
     console.log(this.data.scrollTopId);
   },
   //获取文字信息
   getWords: function (e) {
     var id = e.target.id;
     this.endWords = id;
     isNum = id;
     this.setData({
       showwords: this.endWords
     })
     console.log(2);
     console.log(this.endWords);
   },
   //设置文字信息
   setWords: function (e) {
     var id = e.target.id;
     this.setData({
       scrollTopId: id
     })
     console.log(3);
     console.log(id);
   },
   c_name: function (e) {//点击选项打印值
     console.log(e.currentTarget.dataset.name);
     console.log(e.currentTarget.dataset.id);
     that.setData({ cat_variety: e.currentTarget.dataset.name });//点击品种设置猫的种类
   },
  
   // 滑动选择
   chMove: function (e) {
    //  console.log(e)//???????????????????????????????????????????/
     var y = e.touches[0].clientY;
     var offsettop = e.currentTarget.offsetTop;
     var height = 0;
     var that = this;
     ;
     var cityarr = ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"]
     // 获取y轴最大值
     wx.getSystemInfo({
       success: function (res) {
         height = res.windowHeight - 10;
       }
     });
     //判断选择区域,只有在选择区才会生效
     if (y > offsettop && y < height) {
       // console.log((y-offsettop)/lineHeight)
       var num = parseInt((y - offsettop) / lineHeight);
       endWords = cityarr[num];
       // 这里 把endWords 绑定到this 上，是为了手指离开事件获取值
       that.endWords = endWords;
     };
     //去除重复，为了防止每次移动都赋值 ,这里限制值有变化后才会有赋值操作，
     //DOTO 这里暂时还有问题，还是比较卡，待优化
     if (isNum != num) {
       // console.log(isNum);
       isNum = num;
       that.setData({
         showwords: that.endWords
       })
     }
   },
   inputchange: function (e) {//当搜索框内容改变时触发
     that.setData({ search_content: e.detail.value });//
   },
   search_btn: function () {//点击搜索时
     for (var i = 0; i < that.data.All_variety.length;i++)
     {
       if (that.data.All_variety[i].name == that.data.search_content){
         that.setData({ scrollTopId: that.data.All_variety[i].letter});
         that.setData({ cat_variety: that.data.All_variety[i].name});//点击品种设置猫的种类
         return;
        }
     }
    //弹出提示框查无此类
   },
   toast:function(s){
     wx.showToast({
       title: s,
       image: '../../images/g.png',
       duration: 2000
     })
   }

})  